package com.om.exposed;

public class Driver {

	private static final int RUNS = 100;
	private static final int THREADS = 2;
	protected static final int LOOPS = 2000;

	public static void main(String[] args) throws Exception {
		int passed = 0;
		
		for (int i = 0; i < RUNS; ++i)
			if(exerciseObjectWithValue(i))
				++passed;
		
		System.out.println("Incremented Correctly: " + passed);
	}

	private static boolean exerciseObjectWithValue(int runNumber)
			throws Exception {
		final ObjectWithValue object = new ObjectWithValue();

		Runnable incrementValue = new Runnable() {
			public void run() {
				for (int i = 0; i < LOOPS; ++i)
					object.incrementValue();
			}
		};

		Thread[] threads = new Thread[THREADS];

		for (int i = 0; i < threads.length; ++i)
			threads[i] = new Thread(incrementValue);

		for (Thread t : threads)
			t.start();
		for (Thread t : threads)
			t.join();

		int expected = LOOPS * THREADS;
		System.out.printf("%3d: Expected: %d, Actual: %d\n", runNumber,
				expected, object.getValue());
		return expected == object.getValue();
	}
}
